#define _CRT_SECURE_NO_WARNINGS
#include "heap.h"

void HPInit(HP* php) {
	assert(php);
	php->arr = NULL;
	php->size = php->capacity = 0;
}

void HPDestroy(HP* php) {
	assert(php);
	if (php->arr) {
		free(php->arr);
	}
	HPInit(php);
}
void Swap(HPDataType* arr, int x, int y) {
	HPDataType tmp;
	tmp = arr[x];
	arr[x] = arr[y];
	arr[y] = tmp;
}
void AdjustUp(HPDataType* arr, int child) {
	int parent = (child - 1) / 2;
	while (child != 0 && arr[child] > arr[parent]) {
		Swap(arr, child, parent);
		child = parent;
		parent = (child - 1) / 2;
	}
}
void AdjustDown(HPDataType* arr, int parent, int size) {
	int child = 1;
	while (child <= size - 1) {
		if (child < size - 1 && arr[child] < arr[child + 1])
			child++;
		if (arr[parent] < arr[child])
			Swap(arr, child, parent);
		parent = child;
		child = parent * 2 + 1;
	}
}
HPDataType HPTop(HP* php) {
	assert(php && php->size);
	return php->arr[0];
}
void HPPrint(HP* php) {
	int sz = php->size, i = 0;
	for (i = 0; i < sz; i++) {
		printf("%d ", php->arr[i]);
	}
	printf("\n");
}
bool HPEmpty(HP* php) {
	return (php->size == 0);
}
void HPPush(HP* php, HPDataType x) {
	assert(php);
	if (php->size == php->capacity) {
		int newCapacity = (php->capacity) ? 2 * php->capacity : 4;
		HPDataType* tmp = (HPDataType*)realloc(php->arr, newCapacity * sizeof(HPDataType));
		if (tmp == NULL) {
			perror("realloc fail!");
			exit(1);
		}
		php->arr = tmp;
		php->capacity = newCapacity;
	}
	php->arr[php->size] = x;
	AdjustUp(php->arr, php->size);
	php->size++;
}

void HPPop(HP* php) {
	assert(php);
	Swap(php->arr, 0, php->size - 1);
	php->size--;
	AdjustDown(php->arr, 0, php->size);
}